import tkinter
import tkinter.filedialog
from tkinter import messagebox

from io import BytesIO

import cv2
import numpy as np
import time

top = tkinter.Tk()
top.title("图片压缩工具")
top.geometry('300x300')
# 不可调整大小
top.resizable(False, False)

def choose_fiel():
    selectFileName = tkinter.filedialog.askopenfilename(title='选择文件')  # 选择文件
    e.set(selectFileName)



# 选择文件
e = tkinter.StringVar()
e_entry = tkinter.Entry(top, width=25, textvariable=e)
e_entry.place(x=10, y=10)
# e_entry.pack()

select_file_button = tkinter.Button(top, width=10, text="选择图片", command=choose_fiel)
select_file_button.place(x=200, y=6)


def choose_directory():
    selectDirectory = tkinter.filedialog.askdirectory(title='选择存放目录')  # 选择文件
    dir.set(selectDirectory)


# 选择存放目录

dir = tkinter.StringVar()
dir_entry = tkinter.Entry(top, width=25, textvariable=dir)
dir_entry.place(x=10, y=60)

save_directory_but = tkinter.Button(top, width=10, text="选择存储位置", command=choose_directory);
save_directory_but.place(x=200, y=50)

# 压缩大小值


text = tkinter.Label(top, text="请输入要压缩的大小（单位kb）")
text.place(x=10, y=110)

size = tkinter.IntVar()
size_entry = tkinter.Entry(top, width=10, textvariable=text)
size_entry.place(x=200, y=110)

start_button = tkinter.Button(top, height=2, width=15, text="开始压缩", command=lambda: compress_func(e_entry.get()))
start_button.place(x=100, y=180)


def compress_func(a):
    try:
        print(size_entry.get())
        imgType = "." + e.get().split(".")[1]
        save_dir= dir.get() + "/" + str(int(time.time())) + imgType
        pic_size = pic_compress(e.get(), save_dir,int( size_entry.get()));
        # print("图片压缩后的大小为(KB)：", pic_size)
        messagebox.showinfo('提示', '压缩成功！ 压缩后的存放位置：' + save_dir)
    except:
        messagebox.showinfo('提示', '压缩失败，请检查是否输入正确！')

# 压缩图片
def pic_compress(pic_path, out_path, target_size=199, quality=99, step=1, pic_type='.jpg'):
    # 读取图片bytes
    with open(pic_path, 'rb') as f:
        pic_byte = f.read()

    img_np = np.frombuffer(pic_byte, np.uint8)
    img_cv = cv2.imdecode(img_np, cv2.IMREAD_ANYCOLOR)

    current_size = len(pic_byte) / 1024
    print("图片压缩前的大小为(KB)：", current_size)
    while current_size > target_size:
        pic_byte = cv2.imencode(pic_type, img_cv, [int(cv2.IMWRITE_JPEG_QUALITY), quality])[1]
        if quality - step < 0:
            break
        quality -= step
        current_size = len(pic_byte) / 1024
    # 保存图片
    with open(out_path, 'wb') as f:
        f.write(BytesIO(pic_byte).getvalue())

    return len(pic_byte) / 1024


top.mainloop()
